<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\controller\Common;
use app\service\billService;
use app\service\commonService;
use app\service\roominfoService;
use app\service\apiService;
use think\Db;
use printing\printDemo;
use invoice\HttpClientService;
use invoice\StaticData;
use invoice\CryptAES;
use invoice\Compress;
use app\common\controller\Sendmsg;
use think\Log;
ini_set('max_execution_time','0');
ini_set('memory_limit','1024M');
class Bill extends Common{
    //根据当前账号信息查询token
    public function pidTokenId(){
        $id = session('id');
        //根据ID查询用户信息
        $adminId = (new commonService())->adminIdInfo($id);
        $usertype = $adminId['usertype'];//角色类型
        session("usertype",$usertype);
        $department = $adminId['department'];//所属部门
        if($usertype == 0){//超级管理员
            //查询所有服务商
            
            $com['service_id'] = (new commonService())->serviceList();
            //查询所有物业
            $com['property_id'] = (new commonService())->propertyList();
            //查询所有小区
            $com['community_id'] = (new commonService())->communityList();
            $com["usertype"]=0;
            $com['com_id'] = Db::name('community')->column('id');;
        }else if($usertype == 3){//服务商
            $com['service_id'] = $department;
            $com["usertype"]=3;
            //查询所有物业
            $com['property_id'] = (new commonService())->serviceIdProperty($department);
            //查询所有小区
            $com['community_id'] = (new commonService())->propertyIdCommunity($com['property_id']);
            $com['com_id']= Db::name('community')->where('property_id','in',$com['property_id'])->column('id');
        }else if($usertype == 1){//物业
            //查询所有小区
            $com["usertype"]=1;
            $com['property_id'] = $department;
            $com['community_id'] = (new commonService())->propertyIdCommunity($department);
            $com['com_id']= Db::name('community')->where('property_id','in',$department)->column('id');
        }else if($usertype == 2){//小区
            $com["usertype"]=2;
            $com['community_id'] = (new commonService())->communityIdCommunity($department);
            $com['com_id']=Db::name('community')->where('id',$department)->value('id');
        }
        return $com;
    }
    public function getbillmsg(){
        
        $cost_type=request()->post("cost_type");
        $str="<div class='layui-form-item'> ";
            $str=$str."<div class='layui-input-inline' style='width: 17%;'>"; 
                $str=$str."<input type='text'  required='' lay-verify='required'  autocomplete='off' class='layui-input'   value='".$cost_type."' readonly name='cost_type[]'>";
            $str=$str."</div>";
            
            
            
            $str=$str."<div class='layui-input-inline' style='width: 17%;'>";
                $str=$str."<input type='text' required='' lay-verify='required'  autocomplete='off' class='layui-input'  name='acct_period[]' placeholder='账期'>";
            $str=$str."</div>";
            
            $str=$str."<div class='layui-input-inline' style='width: 17%;'>";
                $str=$str."<input type='text'  required='' lay-verify='required'  autocomplete='off' class='layui-input' name='release_day[]'  placeholder='账单出账日期' class='laydate' value='".date("Ymd")."'>";
            $str=$str."</div>";
            
            $str=$str."<div class='layui-input-inline' style='width: 17%;'>";
                $str=$str."<input type='text'  required='' lay-verify='required'  autocomplete='off' class='layui-input'  name='deadline[]' placeholder='缴费截止日期' class='laydate' >";
            $str=$str."</div>"; 
            
            $str=$str."<div class='layui-input-inline' style='width: 17%;'>";
                $str=$str."<input type='text'  required='' lay-verify='required'  name='bill_amount[]' autocomplete='off' class='layui-input'   placeholder='账单金额'>";
            $str=$str."</div>";
        $str=$str."</div>";
        echo $str;
                
    }
    //查询账单信息
    public function billList(){
        //查询小区信息
        $com = $this->pidTokenId();
        
        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        $this->assign('communitylist',$communitylist);
        //费用类型
        $costtype = (new billService())->costtype($com);
        $this->assign('costtype',$costtype);
        //搜索时
        $data = request()->get();
        $address="";
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            $this->assign('groups', array_values($groups));
                if (!empty($data['group'])) {
                    $address=$data['group'];
                    $buildings = array_unique((new roominfoService())->buildingList($data['community_id'],$data['group']));
                    sort($buildings);
                    $this->assign('buildings',$buildings);
                    if (!empty($data['building'])) {
                        $address=$data['group']."-".$data["building"];
                        $units = array_unique((new roominfoService())->unitList($data['community_id'], $data['group'],$data['building']));
                        sort($units);
                        $this->assign('units',$units);
                        if(!empty($data['unit'])){
                            $address=$data['group']."-".$data["building"]."-".$data['unit'];
                            $rooms = array_unique((new roominfoService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                            sort($rooms);
                            $this->assign('rooms',$rooms);
                            if(!empty($data["room"])){
                                $address=$data['group']."-".$data["building"]."-".$data['unit']."-".$data["room"];
                            }
                        }
                    }
                }                    
                
        }
        if (!empty($data)){
            if(!empty($data['bill_entry_id'])){
                $where['bill_entry_id'] = $data['bill_entry_id'];//账单编号
            }else{
                $where['bill_entry_id'] = "";
            }
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }
            
            if(!empty($data['room_address'])){
                $where['room_address'] = array("like","%".$data['room_address']."%");//楼栋
            }else{
                $where['room_address'] = "";
            }
            if(!empty($address)){
                 $where['room_address'] = array("like","%".$address."%");//楼栋
            }
            if(!empty($data['cost_type'])){
                $where['cost_type'] = $data['cost_type'];//费用类型
            }else{
                $where['cost_type'] = "";
            }
            if(!empty($data['status'])){
                $where['status'] = $data['status'];//账单状态
            }else{
                $where['status'] = "";
            }
            if(!empty($data['tongbu'])){
                $where['tongbu'] = $data['tongbu'];//账单状态
            }else{
                $where['tongbu'] = "";
            }
           
            if(!empty($data['acct_period'])){
                $where['acct_period'] = array('like','%'.$data['acct_period'].'%');//账期
            }else{
                $where['acct_period'] = "";
            }
            if(!empty($data['owner_name'])){
                $whereroom['owner_name'] = array('like','%'.$data['owner_name'].'%');//业主姓名
            }else{
                $whereroom['owner_name'] = "";
            }
            if(!empty($data['owner_phone'])){
                $whereroom['owner_phone'] = $data['owner_phone'];//业主手机号
            }else{
                $whereroom['owner_phone'] = "";
            }
            //var_dump($where);
            $this->assign('whereroom',$whereroom);
            $whereroom = array_filter($whereroom);
            if(!empty($whereroom)){
                $where['out_room_id'] = array('in',(new billService())->whereRoom($community_id,$whereroom));                
            }
            if(!empty($data['gmt_payment_start'])){
                $gmtstart = $data['gmt_payment_start'];
                $this->assign('gmtstart',$gmtstart); 
            }else{
                $gmtstart = '0000-00-00 00:00:00';
            }
            if(!empty($data['gmt_payment_end'])){
                $gmtend = $data['gmt_payment_end'];
                $this->assign('gmtend',$gmtend); 
            }else{
                $gmtend = '9999-12-30 23:59:59';
            }
             
            $this->assign('where',$where);   
            $where = array_filter($where);
            /*if(!empty($data['invoice_type'])){
                $where['invoice_type'] = $data['invoice_type'];//业主手机号
                if($data['invoice_type']=="3"){
                    $where['invoice_type'] = null;
                }
            }else{
                $where['invoice_type'] = null;
            }*/
            
        }else{
            $where=array();
            $gmtstart = '0000-00-00 00:00:00';
            $gmtend = '9999-12-30 23:59:59';
        }
        
        $page = request()->has('page') ? request()->get('page') : 1;
        if($page !== 1){
            $gmtstart= $data['gmtstart'];
            $this->assign('gmtstart',$gmtstart); 
            $gmtend= $data['gmtend'];
            $this->assign('gmtend',$gmtend); 
        }
        $export = $where;
        $export['gmtstart'] = $gmtstart;
        $export['gmtend'] = $gmtend;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        $this->assign('export',$export);
        //查询账单数据
        $billlist = (new billService())->billWhereList($community_id,$page,$where,$gmtstart,$gmtend);

        //查询账单条数
        $number = (new billService())->billWhereNumber($community_id,$where,$gmtstart,$gmtend);
        //Log::write($number,"账单条数");die;
        //查询总金额
        $billsum = (new billService())->billWhereSum($community_id,$where,$gmtstart,$gmtend); 
        $billsum=round($billsum,2);
        //$billsum=0;
       
        if(!empty($billlist)){
            foreach($billlist as $bill){
                //根据小区编号查询小区名称
                $community = (new billService())->communityName($bill['community_id']);
                $bill['community_id'] = $community['community_name'];
                //根据房屋门牌号查询业主信息
                $bill['owner_name'] = (new billService())->billOwnerName($bill['out_room_id']);
                //数据从新存入数组
                $list[] = $bill;
                $this->assign('list',$list);
            }
        }else{
            $this->assign('list',$billlist);
        }
        if(!isset($list)){
            $this->assign('list',$billlist);
        }
        //判断是否有数据
        
        $this->assign('billlist',$billlist);
       
        
        $this->assign('number',$number);
        $this->assign('billsum',$billsum);
        //var_dump($data);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }

        return $this->fetch('bill_list'); 
           
    }
    
    
    //查询账单信息
    public function invoiceList(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        
        $community_id = $com['community_id'];
        $this->assign('communitylist',$communitylist);
        //费用类型
        //echo "<pre>";
        //var_dump($com);die;
        $costtype = (new billService())->costtype($com);
        
        $this->assign('costtype',$costtype);
        
        //搜索时
        $data = request()->get();
        $address="";
        $where['status']="TRADE_SUCCESS";
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            $this->assign('groups', array_values($groups));
            if (!empty($data['group'])) {
                $address=$data['group'];
                $buildings = array_unique((new roominfoService())->buildingList($data['community_id'],$data['group']));
                sort($buildings);
                $this->assign('buildings',$buildings);
                if (!empty($data['building'])) {
                    $address=$data['group']."-".$data["building"];
                    $units = array_unique((new roominfoService())->unitList($data['community_id'], $data['group'],$data['building']));
                    sort($units);
                    $this->assign('units',$units);
                    if(!empty($data['unit'])){
                        $address=$data['group']."-".$data["building"]."-".$data['unit'];
                        $rooms = array_unique((new roominfoService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                        sort($rooms);
                        $this->assign('rooms',$rooms);
                        if(!empty($data["room"])){
                            $address=$data['group']."-".$data["building"]."-".$data['unit']."-".$data["room"];
                        }
                    }
                }
            }

        }
        if (!empty($data)){
            if(!empty($data['bill_entry_id'])){
                $where['bill_entry_id'] = $data['bill_entry_id'];//账单编号
            }else{
                $where['bill_entry_id'] = "";
            }
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }

            
            if(!empty($data['cost_type'])){
                $where['cost_type'] = $data['cost_type'];//费用类型
            }else{
                $where['cost_type'] = "";
            }
            if(!empty($data['invoice_type'])){
                $where['invoice_type'] = $data['invoice_type'];//费用类型
            }else{
                $where['invoice_type'] = "";
            }
           
           
            if(!empty($data['acct_period'])){
                $where['acct_period'] = array('like','%'.$data['acct_period'].'%');//账期
            }else{
                $where['acct_period'] = "";
            }
            if(!empty($data['owner_name'])){
                $whereroom['owner_name'] = array('like','%'.$data['owner_name'].'%');//业主姓名
            }else{
                $whereroom['owner_name'] = "";
            }
            if(!empty($data['owner_phone'])){
                $whereroom['owner_phone'] = $data['owner_phone'];//业主手机号
            }else{
                $whereroom['owner_phone'] = "";
            }
            if(!empty($data['owner_name'])){
                $whereroom['owner_name'] = array('like','%'.$data['owner_name'].'%');//业主姓名
            }else{
                $whereroom['owner_name'] = "";
            }
            if(!empty($address)){
                $where['room_address'] = array("like","%".$address."%");//楼栋
            }else{
                $where['room_address'] = "";
            }
            $this->assign('whereroom',$whereroom);
            $whereroom = array_filter($whereroom);
            if(!empty($whereroom)){
                $where['out_room_id'] = array('in',(new billService())->whereRoom($community_id,$whereroom));                
            }
            if(!empty($data['gmt_payment_start'])){
                $gmtstart = $data['gmt_payment_start'];
                $this->assign('gmtstart',$gmtstart); 
            }else{
                $gmtstart = '0000-00-00 00:00:00';
            }
            if(!empty($data['gmt_payment_end'])){
                $gmtend = $data['gmt_payment_end'];
                $this->assign('gmtend',$gmtend); 
            }else{
                $gmtend = '9999-12-30 23:59:59';
            }
             
            $this->assign('where',$where);   
            $where = array_filter($where);
        }else{
            
            $gmtstart = '0000-00-00 00:00:00';
            $gmtend = '9999-12-30 23:59:59';
        }
        
        $page = request()->has('page') ? request()->get('page') : 1;
        if($page !== 1){
            $gmtstart= $data['gmtstart'];
            $this->assign('gmtstart',$gmtstart); 
            $gmtend= $data['gmtend'];
            $this->assign('gmtend',$gmtend); 
        }
        $export = $where;
        
        $export['gmtstart'] = $gmtstart;
        $export['gmtend'] = $gmtend;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        $this->assign('export',$export);
        //查询账单数据
        $billlist = (new billService())->invoiceWhereList($community_id,$page,$where,$gmtstart,$gmtend);

        //查询账单条数
        $number = (new billService())->billWhereNumber($community_id,$where,$gmtstart,$gmtend);
        //Log::write($number,"账单条数");die;
        //查询总金额
        $billsum = (new billService())->billWhereSum($community_id,$where,$gmtstart,$gmtend); 
        $billsum=round($billsum,2);
        //$billsum=0;
       
        if(!empty($billlist)){
            foreach($billlist as $bill){
                //根据小区编号查询小区名称
                $community = (new billService())->communityName($bill['community_id']);
                $bill['community_id'] = $community['community_name'];
                //根据房屋门牌号查询业主信息
                $roominfo =Db::name('roominfo')->where('out_room_id',$bill["out_room_id"])->find();
                $bill['owner_name']=$roominfo["owner_name"];
                $bill['owner_phone']=$roominfo["owner_phone"];
                //数据从新存入数组
                $list[] = $bill;
                $this->assign('list',$list);
            }
        }else{
            $this->assign('list',$billlist);
        }
        if(!isset($list)){
            $this->assign('list',$billlist);
        }
        //判断是否有数据
        
        $this->assign('billlist',$billlist);
       
        
        $this->assign('number',$number);
        $this->assign('billsum',$billsum);
        //var_dump($data);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }

        return $this->fetch('invoice_list'); 
           
    }

    //导出账单数据
    public function invoiceExportExcel(){
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        //Log::write(request()->param(),"账单导出参数");
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $billList = (new billService())->billEntryIdInfo($id);
            if(empty($billList)){
                return json(['error' => '没有账单数据']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $community_id = $com['community_id'];
            $where = json_decode($export,true);
            $gmtstart = $where['gmtstart'];
            $gmtend = $where['gmtend'];
            unset($where['gmtstart']);
            unset($where['gmtend']);
            $billList = (new billService())->billWhereExport($community_id,$where,$gmtstart,$gmtend);

            if(empty($billList)){
                return json(['error' => '没有账单数据']);
            }
        }
        //var_dump($billList);die;
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '支付宝账单编号')
            ->setCellValue('B1', '小区名称')
            ->setCellValue('C1', '完整门牌号')
            ->setCellValue('D1', '业主姓名')
            ->setCellValue('E1', '业主电话')
            ->setCellValue('F1', '费用类型')
            ->setCellValue('G1', '账期')
            ->setCellValue('H1', '出账日期')
            ->setCellValue('I1', '截止日期')
            ->setCellValue('J1', '账单金额')
            ->setCellValue('K1', '付款状态')
            ->setCellValue('L1', '付款类型')
            ->setCellValue('M1', '付款时间')
            ->setCellValue('N1', '账单备注')
            ->setCellValue('O1', '发票代码')
            ->setCellValue('P1', '发票号码');

        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
        $count = count($billList);  //计算有多少条数据
        for ($i = 2; $i <= $count+1; $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $billList[$i-2]["bill_entry_id"]);
            //根据小区ID查询小区名称
            $commId = $billList[$i-2]["community_id"];
            $communityName = (new roominfoService())->communityIdName($commId);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $communityName['community_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $billList[$i-2]["room_address"]);
            //根据完整门牌号查询业主信息
            $address = $billList[$i-2]["room_address"];
            $owner = (new billService())->roomId($commId,$address);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $owner['owner_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $owner['owner_phone']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $billList[$i-2]["cost_type"]);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $billList[$i-2]["acct_period"]);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $billList[$i-2]["release_day"]);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $billList[$i-2]["deadline"]);
            $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $billList[$i-2]["bill_entry_amount"]);


            //判断账单状态
            if($billList[$i-2]["status"] == 'TRADE_SUCCESS'){
                $status = '已付款';
            }elseif($billList[$i-2]["status"] == 'UNDER_PAYMENT'){
                $status = '待支付';
            }elseif($billList[$i-2]["status"] == 'WAIT_PAYMENT'){
                $status = '待缴费';
            }elseif($billList[$i-2]["status"] == 'OUT_OF_DATE'){
                $status = '已逾期';
            }
            $objPHPExcel->getActiveSheet()->setCellValue('K' . $i, $status);
            $objPHPExcel->getActiveSheet()->setCellValue('L' . $i, $billList[$i-2]["pay_type"]);
            $objPHPExcel->getActiveSheet()->setCellValue('M' . $i, $billList[$i-2]["gmt_payment"]);

            $objPHPExcel->getActiveSheet()->setCellValue('N' . $i, $billList[$i-2]["remarks"]);
            $objPHPExcel->getActiveSheet()->setCellValue('O' . $i, $billList[$i-2]["invoiceCode"]);
            $objPHPExcel->getActiveSheet()->setCellValue('P' . $i, $billList[$i-2]["invoiceNum"]);
        }
        $objPHPExcel->getActiveSheet()->setTitle('发票信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        header('Content-Disposition: attachment;filename="发票信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007"); //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }
    
    
    
    //查询账单信息
    public function billList2(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        $this->assign('communitylist',$communitylist);
        //费用类型
        $costtype = (new billService())->costtype($com);
        $this->assign('costtype',$costtype);
        //搜索时
        $data = request()->get();
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            $this->assign('groups', array_values($groups));
                if (empty($data['group'])) {
                    $data['group'] = '';
                }                    
                $buildings = array_unique((new roominfoService())->buildingList($data['community_id'],$data['group']));
                sort($buildings);
                $this->assign('buildings',$buildings);
                if (!empty($data['building'])) {
                    $units = array_unique((new roominfoService())->unitList($data['community_id'], $data['group'],$data['building']));
                    sort($units);
                    $this->assign('units',$units);
                    if(!empty($data['unit'])){
                        $rooms = array_unique((new roominfoService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                        sort($rooms);
                        $this->assign('rooms',$rooms);
                    }
                }
        }
        if (!empty($data)){
            if(!empty($data['bill_entry_id'])){
                $where['bill_entry_id'] = $data['bill_entry_id'];//账单编号
            }else{
                $where['bill_entry_id'] = "";
            }
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }
            if(!empty($data['group'])){
                if(empty($data['building'])){
                    $where['room_address'] = array('like',$data['group'].'%');//完整门牌号
                }elseif(empty($data['unit'])){
                    $where['room_address'] = array('like',$data['group'].$data['building'].'%');//完整门牌号
                }elseif(empty($data['room'])){
                    $where['room_address'] = array('like',$data['group'].$data['building'].$data['unit'].'%');//完整门牌号
                }else{
                    $where['room_address'] = array('like',$data['group'].$data['building'].$data['unit'].$data['room'].'%');//完整门牌号
                }
            }else{
                if(empty($data['building'])){
                    $where['room_address'] = array('like','%');//完整门牌号
                }elseif(empty($data['unit'])){
                    $where['room_address'] = array('like',$data['building'].'%');//完整门牌号
                }elseif(empty($data['room'])){
                    $where['room_address'] = array('like',$data['building'].$data['unit'].'%');//完整门牌号
                }else{
                    $where['room_address'] = array('like',$data['building'].$data['unit'].$data['room'].'%');//完整门牌号
                }
            }
            if(!empty($data['cost_type'])){
                $where['cost_type'] = $data['cost_type'];//费用类型
            }else{
                $where['cost_type'] = "";
            }
            if(!empty($data['status'])){
                $where['status'] = $data['status'];//账单状态
            }else{
                $where['status'] = "";
            }
            if(!empty($data['tongbu'])){
                $where['tongbu'] = $data['tongbu'];//账单状态
            }else{
                $where['tongbu'] = "";
            }
            if(!empty($data['acct_period'])){
                $where['acct_period'] = array('like','%'.$data['acct_period'].'%');//账期
            }else{
                $where['acct_period'] = "";
            }
            if(!empty($data['owner_name'])){
                $whereroom['owner_name'] = array('like','%'.$data['owner_name'].'%');//业主姓名
            }else{
                $whereroom['owner_name'] = "";
            }
            if(!empty($data['owner_phone'])){
                $whereroom['owner_phone'] = $data['owner_phone'];//业主手机号
            }else{
                $whereroom['owner_phone'] = "";
            }
            
            $this->assign('whereroom',$whereroom);
            $whereroom = array_filter($whereroom);
            if(!empty($whereroom)){
                $where['out_room_id'] = array('in',(new billService())->whereRoom($community_id,$whereroom));                
            }
            if(!empty($data['gmt_payment_start'])){
                $gmtstart = $data['gmt_payment_start'];
                $this->assign('gmtstart',$gmtstart); 
            }else{
                $gmtstart = '0000-00-00 00:00:00';
            }
            if(!empty($data['gmt_payment_end'])){
                $gmtend = $data['gmt_payment_end'];
                $this->assign('gmtend',$gmtend); 
            }else{
                $gmtend = '9999-12-30 23:59:59';
            }
             
            $this->assign('where',$where);   
            $where = array_filter($where);
        }else{
            $where=array();
            $gmtstart = '0000-00-00 00:00:00';
            $gmtend = '9999-12-30 23:59:59';
        }
        $page = request()->has('page') ? request()->get('page') : 1;
        if($page !== 1){
            $gmtstart= $data['gmtstart'];
            $this->assign('gmtstart',$gmtstart); 
            $gmtend= $data['gmtend'];
            $this->assign('gmtend',$gmtend); 
        }
        var_dump($where);
        $export = $where;
        $export['gmtstart'] = $gmtstart;
        $export['gmtend'] = $gmtend;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        $this->assign('export',$export);
        //查询账单数据
        $billlist = (new billService())->billWhereList2($community_id,$page,$where,$gmtstart,$gmtend);
        //查询账单条数
        $number = (new billService())->billWhereNumber($community_id,$where,$gmtstart,$gmtend);
        //查询总金额
        $billsum = (new billService())->billWhereSum($community_id,$where,$gmtstart,$gmtend);
        //判断是否有数据
        if(!empty($number)){
            foreach($billlist as $bill){
                //根据小区编号查询小区名称
                $community = (new billService())->communityName($bill['community_id']);
                $bill['community_id'] = $community['community_name'];
                //根据房屋门牌号查询业主信息
                $bill['owner_name'] = (new billService())->billOwnerName($bill['out_room_id']);
                //数据从新存入数组
                $list[] = $bill;
                $this->assign('list',$list);
            }
        }else{
            $this->assign('list',$billlist);
        }
        $this->assign('billlist',$billlist);
        
        $this->assign('number',$number);
        $this->assign('billsum',$billsum);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }

        return $this->fetch('bill_list2'); 
           
    }

    //查询账单信息
    public function unpaybillList(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        $this->assign('communitylist',$communitylist);
        //费用类型
        $costtype = (new billService())->costtype($com);
        $this->assign('costtype',$costtype);
        //搜索时
        $data = request()->get();
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            $this->assign('groups', array_values($groups));
                if (empty($data['group'])) {
                    $data['group'] = '';
                }                    
                $buildings = array_unique((new roominfoService())->buildingList($data['community_id'],$data['group']));
                sort($buildings);
                $this->assign('buildings',$buildings);
                if (!empty($data['building'])) {
                    $units = array_unique((new roominfoService())->unitList($data['community_id'], $data['group'],$data['building']));
                    sort($units);
                    $this->assign('units',$units);
                    if(!empty($data['unit'])){
                        $rooms = array_unique((new roominfoService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                        sort($rooms);
                        $this->assign('rooms',$rooms);
                    }
                }
        }
        
        if (!empty($data)){
            if(!empty($data['bill_entry_id'])){
                $where['bill_entry_id'] = $data['bill_entry_id'];//账单编号
            }else{
                $where['bill_entry_id'] = "";
            }
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }
            if(!empty($data['group'])){
                if(empty($data['building'])){
                    $where['room_address'] = array('like',$data['group'].'%');//完整门牌号
                }elseif(empty($data['unit'])){
                    $where['room_address'] = array('like',$data['group']."-".$data['building'].'%');//完整门牌号
                }elseif(empty($data['room'])){
                    $where['room_address'] = array('like',$data['group']."-".$data['building']."-".$data['unit'].'%');//完整门牌号
                }else{
                    $where['room_address'] = array('like',$data['group']."-".$data['building']."-".$data['unit']."-".$data['room'].'%');//完整门牌号
                }
            }else{
                if(empty($data['building'])){
                    $where['room_address'] = array('like','%');//完整门牌号
                }elseif(empty($data['unit'])){
                    $where['room_address'] = array('like',$data['building'].'%');//完整门牌号
                }elseif(empty($data['room'])){
                    $where['room_address'] = array('like',$data['building'].$data['unit'].'%');//完整门牌号
                }else{
                    $where['room_address'] = array('like',$data['building'].$data['unit'].$data['room'].'%');//完整门牌号
                }
            }
            if(!empty($data['cost_type'])){
                $where['cost_type'] = $data['cost_type'];//费用类型
            }else{
                $where['cost_type'] = "";
            }
            
            if(!empty($data['acct_period'])){
                $where['acct_period'] = array('like','%'.$data['acct_period'].'%');//账期
            }else{
                $where['acct_period'] = "";
            }
            if(!empty($data['owner_name'])){
                $whereroom['owner_name'] = array('like','%'.$data['owner_name'].'%');//业主姓名
            }else{
                $whereroom['owner_name'] = "";
            }
            if(!empty($data['owner_phone'])){
                $whereroom['owner_phone'] = $data['owner_phone'];//业主手机号
            }else{
                $whereroom['owner_phone'] = "";
            }
            
            $this->assign('whereroom',$whereroom);
            $whereroom = array_filter($whereroom);
            if(!empty($whereroom)){
                $where['out_room_id'] = array('in',(new billService())->whereRoom($community_id,$whereroom));                
            }
            if(!empty($data['gmt_payment_start'])){
                $gmtstart = $data['gmt_payment_start'];
                $this->assign('gmtstart',$gmtstart); 
            }else{
                $gmtstart = '0000-00-00 00:00:00';
            }
            if(!empty($data['gmt_payment_end'])){
                $gmtend = $data['gmt_payment_end'];
                $this->assign('gmtend',$gmtend); 
            }else{
                $gmtend = '9999-12-30 23:59:59';
            }
             
            $this->assign('where',$where);   
            $where = array_filter($where);
        }else{
            $where=array();
            $gmtstart = '0000-00-00 00:00:00';
            $gmtend = '9999-12-30 23:59:59';
        }
        $page = request()->has('page') ? request()->get('page') : 1;
        if($page !== 1){
            $gmtstart= $data['gmtstart'];
            $this->assign('gmtstart',$gmtstart); 
            $gmtend= $data['gmtend'];
            $this->assign('gmtend',$gmtend); 
        }
        $where['status']="WAIT_PAYMENT";
        $export = $where;
        $export['gmtstart'] = $gmtstart;
        $export['gmtend'] = $gmtend;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        $this->assign('export',$export);
        //查询账单数据
        //var_dump($where);
        $billlist = (new billService())->unpaybillWhereList($community_id,$page,$where,$gmtstart,$gmtend);
        
        //查询账单条数
        $numberlist = (new billService())->billWhereNumber($community_id,$where,$gmtstart,$gmtend);
        //查询总金额
        $billsum = (new billService())->billWhereSum($community_id,$where,$gmtstart,$gmtend);
        //判断是否有数据
        if(!empty($numberlist)){
            foreach($billlist as $bill){
                //根据小区编号查询小区名称
                $community = (new billService())->communityName($bill['community_id']);
                $bill['community_id'] = $community['community_name'];
                //根据房屋门牌号查询业主信息
                $bill['owner_name'] = (new billService())->billOwnerName($bill['out_room_id']);
                //数据从新存入数组
                $list[] = $bill;
                $this->assign('list',$list);
            }
        }else{
            $this->assign('list',$billlist);
        }
        $this->assign('billlist',$billlist);
        //$this->assign('list',$billlist);
        $number = $numberlist;
        $this->assign('number',$number);
        $this->assign('billsum',$billsum);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }

        return $this->fetch('unpay_bill_list'); 
           
    }


    //添加账单信息
    public function billAdd(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        $this->assign('communitylist',$communitylist);
        //查询费用类型
        $type = (new billService())->costtype($com);
        $this->assign('type',$type);

        if(request()->isPOST()){
            //获取表单数据
            $data = request()->post();
            
            //查询房屋编号
           
            $roominfo = (new billService())->roominfo($data['community_id'],$data['group'],$data['building'],$data['unit'],$data['room']);
            if(empty( $roominfo)){
                $this->error('房屋信息错误',url('billAdd'));
            }
            $data['room_address'] =$roominfo["address"];
            $data['out_room_id'] = $roominfo['out_room_id'];
            //生成业务标识
            $data['batch_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(8);
            $data['bill_entry_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(6);
            $data['tongbu'] = '2';
            $data['status'] = 'WAIT_PAYMENT';
            $data['release_day'] = date("Ymd");
            $data['deadline'] = date("Ymd",strtotime("+3years",time()));
            //添加时间
            $data['time'] = date('Y-m-d H:i:s',time());
            unset($data['group']);
            unset($data['building']);
            unset($data['unit']);
            unset($data['room']);
            //数据插入到数据库
            $result = (new billService())->billAdd($data);
            //判断数据是否插入成功
            if($result){
                return "ok";
                $this->success('添加账单成功',url('billList'));
            }else{
                return "error";
                $this->error('添加账单失败',url('billAdd'));
            }
        }else{
           return $this->fetch('bill_add'); 
        }
    }

    //修改账单信息
    public function billEdit(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        $this->assign('communitylist',$communitylist);
        //查询费用类型
        $type = (new billService())->costtype($com);
        $this->assign('type',$type);
        
        if(request()->isGet()){
            $id = request()->param('id');
            if(!isset($id) && empty($id)){
                $this->error('账单不存在',url('billList'));
            }
            //查询指定ID账单信息
            $info = (new billService())->billIdinfo($id);
            if($info['status'] == 'TRADE_SUCCESS'){
                return json(['info' => '账单已付款，不可更改']);
            }
            
            //根据小区编号查询小区名称
            $info['community_name'] = (new billService())->communityName($info['community_id'])['community_name'];
            $this->assign('info',$info);
            return $this->fetch('bill_edit');
        }else{
            //获取表单信息
            $data = request()->post();
            $info = (new billService())->billIdinfo($data["id"]);
            if($info['status'] == 'TRADE_SUCCESS'){
                return json(['info' => '账单已付款，不可更改']);
            }
             //根据小区community_id查询物业token
            $token = (new billService())->billinfoToken($info['community_id']);
            if($info["tongbu"]=="1"){
                $api = new apiService(config('app')['roombilledit'], 'https://openapi.alipay.com/gateway.do');
                
                $res = $api->roomBillEdit(json_encode(['batch_id' => $info['batch_id'], 'community_id' =>  $info['community_id'], 'bill_entry_id' => $info['bill_entry_id'],'out_room_id' => $info['out_room_id'], 'room_address' => $info['room_address'], 'cost_type' => $data['cost_type'], 'bill_entry_amount' => $data['bill_entry_amount'], 'acct_period' => $data['acct_period'], 'release_day' => $data['release_day'], 'deadline' => $data['deadline'],  'token' => $token]));
                
                //判断是否存入支付宝
                if (!isset($res['error'])){
                   $resu=$res['success'];
                   if(isset($resu->alive_bill_entry_list)){
                       return "账单支付中无法修改";
                   }
                    
                    $result = (new billService())->billEdit($data);
                    
                    //判断数据是否插入成功
                    if($result){
                        return "修改账单成功";
                        $this->success('修改账单成功',url('billList'));
                    }else{
                        return "修改账单失败";
                        $this->error('修改账单失败',url('billEdit'));
                    }
                }else{
                    return json(['error' => $res['error']]); 
                }
            }else{
                $result = (new billService())->billEdit($data);
                //判断数据是否插入成功
                if($result){
                    $this->success('修改账单成功',url('billList'));
                }else{
                    $this->error('修改账单失败',url('billEdit'));
                }
            }
           
            

        }
    }

    //备注
    public function remarks(){
        if(request()->isGet()){
            $id = request()->get('id');
            if(!isset($id) && empty($id)){
                $this->error('账单不存在');
            }
            //查询指定ID账单信息
            $info = (new billService())->billIdinfo($id);
            $this->assign('info',$info);
            return $this->fetch('bill_remarks');
        }else{
            $data['id'] = request()->post('id');
            $data['remarks'] = request()->post('remarks');
            if(empty(request()->post('ticket'))){
                $data['ticket'] = null;
            }else{
                $data['ticket'] = request()->post('ticket');
            }
            $result = (new billService())->billEdit($data);
            //判断数据是否插入成功
            if($result){
                $this->success('添加备注成功',url('billList'));
            }else{
                $this->error('添加备注失败',url('remarks'));
            }
        }
    }
    public function billDel2()
    {
        //判断是否存在该数据
        $id = explode(',',request()->param('id'));        
        $info = (new billService())->billEntryIdInfo($id);
        if (count($info) != count($id)) {
            return json(['error' => '账单信息不完整']);
        }
        foreach($info as $inf){
            if($inf['status'] == 'TRADE_SUCCESS'){
                return json(['error' => '账单已付款,不能被删除']);
            }
            if($inf['tongbu'] == 2){
                $result = (new billService())->deleteBillInfo($inf['id']);
                if(empty($result)){
                    return json(['error' => '账单删除失败']); 
                } 
            }else{
                //根据小区community_id查询物业token
                $token = (new billService())->billinfoToken($inf['community_id']);
                if($token){
                    //将数据传入api
                    $api = new apiService(config('app')['roombilldel'], 'https://openapi.alipay.com/gateway.do');
                    $res = $api->roomBillDel(json_encode(['community_id' =>  $inf['community_id'], 'bill_entry_id' => $inf['bill_entry_id'], 'token' => $token]));
                    if (!isset($res['error'])) {
                        $result = (new billService())->deleteBillInfo($inf['id']);
                        if(empty($result)){
                            return json(['error' => '账单删除失败']);
                        } 
                    }else{
                        return json(['error' => $res['error']]);
                    }
                }else{
                    return json(['error' => '账单信息不存在']); 
                }
            }
        }
        return json(['info' => '删除成功']);   
    }
    //批量删除账单
    public function billDel(){
        //判断是否存在该数据
        $id = explode(',',request()->param('id'));        
        $billlist = (new billService())->billEntryIdInfo($id);
        if (count($billlist) != count($id)) {
            return json(['error' => '账单信息不完整']);
        }
        
        //查询账单同步的状态
        $tongbu=Db::table("bill")->where("id","in",$id)->distinct("tongbu")->field("tongbu")->select();
        if(count($tongbu)!="1"){
            return json(['error' => '请分别删除已同步未同步的账单']);
        }
        
        $community=Db::table("bill")->where("id","in",$id)->distinct("community_id")->field("community_id")->select();
        if(count($community)!="1"){
            return json(['error' => '账单不是同一小区无法批量同步']);
        }
        $community_id=$community[0]["community_id"];
        $batch_id=date('YmdHis', time()).\util\Tool::getRandomStr(6);//请求批次号;
        
        
        if($tongbu[0]["tongbu"]=="1"){
            //批量删除已同步账单
            $token = (new roominfoService())->communityToken($community_id);
            if($token){
                //将数据传入api
                $api = new apiService(config('app')['roombilldel'], 'https://openapi.alipay.com/gateway.do');
                $res = $api->roomBillDel2(json_encode(['community_id' =>  $community_id, 'token' => $token]),json_encode($billlist));
                if (!isset($res['error'])) {
                    foreach($billlist as $inf){
                        $result = (new billService())->deleteBillInfo($inf['id']);
                    }
                    return json(['info' => '账单删除成功']);
                }else{
                    return json(['error' => $res['error']]);
                }
            }else{
                return json(['error' => '账单信息不存在']); 
            }
        }else if($tongbu[0]["tongbu"]=="2"){
            //批量删除未已同步账单
            foreach($billlist as $inf){
                $result = (new billService())->deleteBillInfo($inf['id']);
            }
            return json(['info' => '账单删除成功']);
        }else{
            return json(['error' => '账单删除失败']);
        }
             
    }
	
	//批量删除账单
    public function billpayDel(){
        //判断是否存在该数据
        $id = explode(',',request()->param('id'));        
        $billlist = (new billService())->billEntryIdInfo($id);
        if (count($billlist) != count($id)) {
            return json(['error' => '账单信息不完整']);
        }
        $community=Db::table("bill")->where("id","in",$id)->distinct("community_id")->field("community_id")->select();
        if(count($community)!="1"){
            return json(['error' => '账单不是同一小区无法批量同步']);
        }
        
        //查询账单是否有未付款的账单
        $paystatus=Db::table("bill")->where("id","in",$id)->distinct("status")->field("status")->select();
        if(count($paystatus)!="1"){
            return json(['error' => '请分别删除已付款的账单']);
        }
        
        
        if($paystatus[0]["status"]=="TRADE_SUCCESS"){
            //批量删除未已同步账单
            foreach($billlist as $inf){
                $result = (new billService())->deleteBillInfo($inf['id']);
            }
            return json(['info' => '账单删除成功']);
        }else{
            return json(['error' => '账单删除失败']);
        }
             
    }
	public function billdelidtest(){
        $id=request()->get("id");
        $result = (new billService())->deleteBillInfo($id);
        
        if($result){
            $this->success("删除账单成功");
        }else{
            $this->error("删除账单失败");
        }
    }

	public function billDelId(){
		$id=request()->get("id");
		$info = Db::table("bill")->find($id);
		$token = (new billService())->billinfoToken($info['community_id']);
		$api = new apiService(config('app')['roombilldel'], 'https://openapi.alipay.com/gateway.do');
		if($info['status'] == 'TRADE_SUCCESS'){
		        $result = (new billService())->deleteBillInfo($info['id']);
                if(empty($result)){
					return json(['error' => '账单删除失败']);
				}else{
				    $url=url('billlist');
				    $this->success("删除成功");
				    //echo "<script>alert('删除成功');location.href='$url'</script>";
				    //die;
					//return json(['msg' => '账单删除成功']);
				}
				/*$res = $api->roomBillDel(json_encode(['community_id' =>  $info['community_id'], 'bill_entry_id' => $info['bill_entry_id'], 'token' => $token]));
				var_dump($res);
				if (!isset($res['error'])){
					return json(['msg' => '账单删除成功']);
				}else{
					return json(['error' => '账单删除失败']);
				}*/
                
        }else{
			//未同步
			if($info['tongbu'] == 2){
                $result = (new billService())->deleteBillInfo($info['id']);
                if(empty($result)){
                    return json(['error' => '账单删除失败']); 
                }else{
                    $this->success("删除成功");
				    /*$url=url('billlist');
				    echo "<script>alert('删除成功');window.location.href='$url'</script>";
				    die;
					return json(['msg' => '账单删除成功']);*/
				}
            }else{
                
				$res = $api->roomBillDel(json_encode(['community_id' =>  $info['community_id'], 'bill_entry_id' => $info['bill_entry_id'], 'token' => $token]));
				//var_dump($res);
				if (!isset($res['error'])) {
					$result = (new billService())->deleteBillInfo($info['id']);
					if(empty($result)){
					    
						return json(['error' => '账单删除失败']);
					}else{
					    $url=url('billlist');
					    $this->success("删除成功");
    				    //echo "<script>alert('删除成功');window.location.href='$url'</script>";
    				    //die;
						//return json(['msg' => '账单删除成功']);
					}
				}else{
				    /*if($res['error']=="指定的明细条目不存在"){
				        $result2 = (new billService())->deleteBillInfo($info['id']);
    					if(empty($result2)){
    					    
    						return json(['error' => '账单删除失败']);
    					}else{
    					    $url=url('billlist');
    					    $this->success("删除成功");
    					}
				    }*/
				    
					return json(['error' => $res['error']]);
				}	
			}
		}
		
	}
	
	public function billquery(){
		$out_room_id="202007220933363QQYAAHY";//20190704104041UE3FSYMH
		$info = Db::table("roominfo")->where('out_room_id',$out_room_id)->find();
		
		echo "<pre>";
		//var_dump($info);
		$token = (new billService())->billinfoToken($info["community_id"]);
		$api = new apiService(config('app')['roombilllist'], 'https://openapi.alipay.com/gateway.do');
		$res = $api->roomBillList(json_encode(['community_id' =>  $info['community_id'], 'out_room_id' => $info['out_room_id'],'batch_id' => "", 'bill_status' => 'WAIT_PAYMENT',  'cost_type' => '' , 'acct_period' => '' , 'release_day' => '' ,'token' => $token]));
		var_dump($res);
	}
	public function delbill(){
        
        $bill_entry_id="20200725194841N2EN4X";
        $billinfo=Db::table("bill")->where("bill_entry_id",$bill_entry_id)->find();
        //$community_id=$billinfo["community_id"];
        $community_id="A47XE1QGS3301";
        $token = (new billService())->billinfoToken($community_id);
        $api = new apiService(config('app')['roombilldel'], 'https://openapi.alipay.com/gateway.do');
        $res = $api->roomBillDel(json_encode(['community_id' =>  $community_id, 'bill_entry_id' => $bill_entry_id, 'token' => $token]));
        var_dump($res);
    }
	
	
	
	
	
    //导入表格数据
    public function billExcel(){
        if(request()->isPOST()){
            //上传excel文件
            $file = request()->file('myfile');
            //移到/public/excel/下
            $info = $file->move(ROOT_PATH.'public'.DS.'excel');
            //上传文件成功
            if ($info) {
                //引入PHPExcel类
                vendor('PHPExcel.PHPExcel.Reader.Excel2007');
                //获取上传后的文件名
                $fileName = $info->getSaveName();
                //文件路径
                $filePath = dir(getcwd())->path.'/excel/'.$fileName;
                //判断文件格式，实例化相应的PHPExcel类，读取excel文件
                $extension = strtolower( pathinfo($fileName, PATHINFO_EXTENSION));
                if ($extension =='xlsx' ) {
                    $objReader = new \PHPExcel_Reader_Excel2007();
                    $objPHPExcel = $objReader ->load($filePath);
                }else if ($extension=='xls'){
                    return "格式xlsx";
                    $objReader = new \PHPExcel_Reader_Excel5(); 
                    $objPHPExcel = $objReader ->load($filePath);
                } else if ($extension=='csv') {
                    $objReader = new \PHPExcel_Reader_CSV();
                    //默认输入字符集
                    $objReader->setInputEncoding('GBK');
                    //默认的分隔符
                    $objReader->setDelimiter(',');
                    //载入文件
                    $objPHPExcel = $objReader ->load($filePath);
                }else{
                    $this->success('文件格式错误',url('billExcel'));
                }  
                //读取excel文件中的第一个工作表
                $sheet = $objPHPExcel->getSheet(0);
                $allRow = $sheet->getHighestRow();  //取得总行数
                //$allColumn = $sheet->getHighestColumn();  //取得总列数
                //从第三行开始插入，第一行是列名
                for ($j=2; $j <= $allRow; $j++) {
                    //生成业务标识
                    $data['batch_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(8);//账单批次号
                    $communityName = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();
                    //根据小区名称查找community_id
                    if(!empty($communityName)){
                        $communityList = (new billService())->communityNameId($communityName);
                        if(!empty($communityList)){
                            $data['community_id'] = $communityList['community_id']; //小区ID
                        }else{
                            $data['community_id'] = '';
                        }  
                    }else{
                        $data['community_id'] = '';
                    }
                    $data['bill_entry_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(6);//账单明细条目
                    $group = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//房屋所在组团
                    
                    $building = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//房屋所在楼栋
                    
                    $unit = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//房屋所在单元
                    
                    $room = $objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();//房屋所在房号
                    
                    $data['room_address'] = $group."-".$building."-".$unit."-".$room;
                    //根据房间门牌号查找房间编号
                    $roominfo = (new billService())->roominfo($data['community_id'],$group,$building,$unit,$room);
                    
                    //Log::write($roominfo,"房屋");
                    

                    $data['cost_type'] = $objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();//费用类型
                    $data['acct_period'] = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();//账期
                    //$data['release_day'] = $objPHPExcel->getActiveSheet()->getCell("J".$j)->getValue();//出账日期
                    //$data['deadline'] = $objPHPExcel->getActiveSheet()->getCell("K".$j)->getValue();//截止日期
                    $data['release_day'] = date("Ymd");
                    $data['deadline'] = date("Ymd",strtotime("+3years",time()));
                    $data['bill_entry_amount'] = $objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();//账单金额
                    $status = $objPHPExcel->getActiveSheet()->getCell("I".$j)->getValue();//状态
                    $data['remarks'] = $objPHPExcel->getActiveSheet()->getCell("J".$j)->getValue();//备注
                    if($status == '已付款'){
                        $data['status'] = 'TRADE_SUCCESS';
                        $data['tongbu'] = '1';
                        $data['pay_type'] = $objPHPExcel->getActiveSheet()->getCell("K".$j)->getValue();//付款类型
                        $data['gmt_payment'] = $objPHPExcel->getActiveSheet()->getCell("L".$j)->getValue();//付款时间
                        
                    }elseif($status == '待付款'){
                        $data['status'] = 'WAIT_PAYMENT';
                        $data['tongbu'] = '2';
                        $data['pay_type'] = '';
                        $data['gmt_payment'] = '';
                        
                    }
                    
                    $data['time'] = date('Y-m-d H:i:s',time());

                    $data = array_filter($data);
                    $number = count($data);
                    // dump($data);exit();
                    
                    if(empty($roominfo)){
                        echo  "第".$j."行房屋信息错误<br/>";
                    }else{
                        $data['out_room_id'] = $roominfo['out_room_id'];//房屋编号
                       
                        //数据插入到数据库并返回主键id
                        //判断账单是否重复
                        $billCostType = (new billService())->billcosttype($data['community_id'],$data['out_room_id'],$data['cost_type'],$data['acct_period']);
                        if(isset($billCostType)){
                            echo "第".$j."行数据重复，导入失败！<br/>";
                        }else{
                            $last_id = (new billService())->billExcelAdd($data);
                            //判断数据是否插入成功
                            if ($last_id) {
                                //echo "第".$j."行导入成功，users表第:".$last_id."条！<br/>";
                            }else{
                                echo "第".$j."行导入失败！<br/>";
                            }  
                        }
                    }
                    
                }
                echo "导入完成<br/>";
            }else{
                $this->success('上传文件失败',url('billExcel'));
            }
        }else{
            return $this->fetch('bill_excel');
        }
    }

    //导入表格数据
    public function billExcel2(){
        if(request()->isPOST()){
            //上传excel文件
            $file = request()->file('myfile');
            //移到/public/excel/下
            $info = $file->move(ROOT_PATH.'public'.DS.'excel');
            //上传文件成功
            if ($info) {
                //引入PHPExcel类
                vendor('PHPExcel.PHPExcel.Reader.Excel2007');
                //获取上传后的文件名
                $fileName = $info->getSaveName();
                //文件路径
                $filePath = dir(getcwd())->path.'/excel/'.$fileName;
                //判断文件格式，实例化相应的PHPExcel类，读取excel文件
                $extension = strtolower( pathinfo($fileName, PATHINFO_EXTENSION));
                if ($extension =='xlsx' || $extension =='xls') {
                    $objReader = new \PHPExcel_Reader_Excel2007();
                    $objPHPExcel = $objReader ->load($filePath);
                } else if ($extension=='csv') {
                    $objReader = new \PHPExcel_Reader_CSV();
                    //默认输入字符集
                    $objReader->setInputEncoding('GBK');
                    //默认的分隔符
                    $objReader->setDelimiter(',');
                    //载入文件
                    $objPHPExcel = $objReader ->load($filePath);
                }else{
                    $this->success('文件格式错误',url('billExcel'));
                }  
                //读取excel文件中的第一个工作表
                $sheet = $objPHPExcel->getSheet(0);
                $allRow = $sheet->getHighestRow();  //取得总行数
                //$allColumn = $sheet->getHighestColumn();  //取得总列数
                //从第三行开始插入，第一行是列名
                for ($j=2; $j <= $allRow; $j++) {
                    //生成业务标识
                    $data['batch_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(8);//账单批次号
                    $communityName = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();
                    //根据小区名称查找community_id
                    if(!empty($communityName)){
                        $communityList = (new billService())->communityNameId($communityName);
                        if(!empty($communityList)){
                            $data['community_id'] = $communityList['community_id']; //小区ID
                        }else{
                            $data['community_id'] = '';
                        }  
                    }else{
                        $data['community_id'] = '';
                    }
                    $data['bill_entry_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(6);//账单明细条目
                    $group = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//房屋所在组团
                    if(!empty($group)){
                        $addr['group'] = $group; 
                    }else{
                        $addr['group'] = ''; 
                    }
                    $building = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//房屋所在楼栋
                    if(!empty($building)){
                        $addr['building'] = $building; 
                    }else{
                        $addr['building'] = ''; 
                    }
                    $unit = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//房屋所在单元
                    if(!empty($unit)){
                        $addr['unit'] = $unit; 
                    }else{
                        $addr['unit'] = ''; 
                    }
                    $room = $objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();//房屋所在房号
                    if(!empty($room)){
                        $addr['room'] = $room; 
                    }else{
                        $addr['room'] = ''; 
                    }
                    if(!empty($addr['building']) && !empty($addr['unit']) &&  !empty($addr['room'])){
                        $data['room_address'] = $addr['group'].$addr['building'].$addr['unit'].$addr['room'];
                        //根据房间门牌号查找房间编号
                        $roomlist = (new billService())->roomId($data['community_id'],$data['room_address']);
                        $data['out_room_id'] = $roomlist['out_room_id'];//房屋编号
                    }else{
                        $data['room_address'] = '';
                    }

                    $data['cost_type'] = $objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();//费用类型
                    $data['acct_period'] = $objPHPExcel->getActiveSheet()->getCell("I".$j)->getValue();//账期
                    $data['release_day'] = $objPHPExcel->getActiveSheet()->getCell("J".$j)->getValue();//出账日期
                    $data['deadline'] = $objPHPExcel->getActiveSheet()->getCell("K".$j)->getValue();//截止日期
                    $data['bill_entry_amount'] = $objPHPExcel->getActiveSheet()->getCell("L".$j)->getValue();//账单金额
                    $status = $objPHPExcel->getActiveSheet()->getCell("M".$j)->getValue();//状态
                    if($status == '已付款'){
                        $data['status'] = 'TRADE_SUCCESS';
                        $data['tongbu'] = '1';
                        $data['pay_type'] = $objPHPExcel->getActiveSheet()->getCell("N".$j)->getValue();//付款类型
                        $data['gmt_payment'] = $objPHPExcel->getActiveSheet()->getCell("O".$j)->getValue();//付款时间
                        $numbers = 14;
                    }elseif($status == '待付款'){
                        $data['status'] = 'WAIT_PAYMENT';
                        $data['tongbu'] = '2';
                        $data['pay_type'] = '';
                        $data['gmt_payment'] = '';
                        $numbers = 12;
                    }
                    $data['remarks'] = $objPHPExcel->getActiveSheet()->getCell("P".$j)->getValue();//备注
                    $data['time'] = date('Y-m-d H:i:s',time());

                    $data = array_filter($data);
                    $number = count($data);
                    // dump($data);exit();
                    if($number >= $numbers && !empty($data['out_room_id'])){
                        //数据插入到数据库并返回主键id
                        //判断账单是否重复
                        $billCostType = (new billService())->billcosttype($data['community_id'],$data['out_room_id'],$data['cost_type'],$data['acct_period']);
                        if(isset($billCostType)){
                            echo "第".$j."行数据重复，导入失败！<br/>";
                        }else{
                            $data["discount_status"]=1;
                            $last_id = (new billService())->billExcelAdd($data);
                            //判断数据是否插入成功
                            if ($last_id) {
                                //echo "第".$j."行导入成功，users表第:".$last_id."条！<br/>";
                            }else{
                                echo "第".$j."行导入失败！<br/>";
                            }  
                        }
                    }else{
                        echo "第".$j."行数据不完整，导入失败！<br/>";
                    }
                }
                echo "导入成功<br/>";
            }else{
                $this->success('上传文件失败',url('billExcel2'));
            }
        }else{
            return $this->fetch('bill_excel2');
        }
    }


    //导出账单数据
    public function billExportExcel(){
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        //Log::write(request()->param(),"账单导出参数");
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $billList = (new billService())->billEntryIdInfo($id);
            if (count($billList) != count($id)) {
                return json(['error' => '账单信息不完整']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $community_id = $com['community_id'];            
            $where = json_decode($export,true);
            $gmtstart = $where['gmtstart'];
            $gmtend = $where['gmtend'];
            unset($where['gmtstart']);
            unset($where['gmtend']);
            $billList = (new billService())->billWhereExport($community_id,$where,$gmtstart,$gmtend);
            if(empty($billList)){
                return json(['error' => '没有账单数据']);
            }
        }
        //var_dump($billList);die;
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '支付宝账单编号')
        ->setCellValue('B1', '小区名称')
        ->setCellValue('C1', '完整门牌号')
        ->setCellValue('D1', '业主姓名')
        ->setCellValue('E1', '业主电话')
        ->setCellValue('F1', '费用类型')
        ->setCellValue('G1', '账期')
        ->setCellValue('H1', '出账日期')
        ->setCellValue('I1', '截止日期')
        ->setCellValue('J1', '账单金额')
        ->setCellValue('K1', '折扣金额')      
        ->setCellValue('L1', '付款状态')
        ->setCellValue('M1', '付款类型')
        ->setCellValue('N1', '付款时间')
        ->setCellValue('O1', '票据号')
        ->setCellValue('P1', '账单备注');

        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
        $count = count($billList);  //计算有多少条数据
        for ($i = 2; $i <= $count+1; $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $billList[$i-2]["bill_entry_id"]);
            //根据小区ID查询小区名称
            $commId = $billList[$i-2]["community_id"];
            $communityName = (new roominfoService())->communityIdName($commId);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $communityName['community_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $billList[$i-2]["room_address"]);
            //根据完整门牌号查询业主信息
            $address = $billList[$i-2]["room_address"];
            $owner = (new billService())->roomId($commId,$address);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $owner['owner_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $owner['owner_phone']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $billList[$i-2]["cost_type"]);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $billList[$i-2]["acct_period"]);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $billList[$i-2]["release_day"]);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $billList[$i-2]["deadline"]);
            $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $billList[$i-2]["bill_entry_amount"]);
            $discount_money="";
            if(!empty($billList[$i-2]["discount_money"]))
            {
                $discount_money_arr=explode("(",$billList[$i-2]["discount_money"]);
                $discount_money=$discount_money_arr[0];
            }
            $objPHPExcel->getActiveSheet()->setCellValue('K' . $i,$discount_money);

            //判断账单状态
            if($billList[$i-2]["status"] == 'TRADE_SUCCESS'){
                $status = '已付款';
            }elseif($billList[$i-2]["status"] == 'UNDER_PAYMENT'){
                $status = '待支付';
            }elseif($billList[$i-2]["status"] == 'WAIT_PAYMENT'){
                $status = '待缴费';
            }elseif($billList[$i-2]["status"] == 'OUT_OF_DATE'){
                $status = '已逾期';
            }
            $objPHPExcel->getActiveSheet()->setCellValue('L' . $i, $status);
            $objPHPExcel->getActiveSheet()->setCellValue('M' . $i, $billList[$i-2]["pay_type"]);
            $objPHPExcel->getActiveSheet()->setCellValue('N' . $i, $billList[$i-2]["gmt_payment"]);
            $objPHPExcel->getActiveSheet()->setCellValue('O' . $i, $billList[$i-2]["ticket"]);
            $objPHPExcel->getActiveSheet()->setCellValue('P' . $i, $billList[$i-2]["remarks"]);
        }
        $objPHPExcel->getActiveSheet()->setTitle('账单信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        header('Content-Disposition: attachment;filename="账单信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007"); //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }

  

    //一键收款查询
    public function onekeyBillList2(){
        if(request()->isPost()){
            //获取账单数据
            $validate = $this->validate(request()->post(),[
                'id|账单'	=>	'require',
                'pay_type|付款类型' => 'require'
            ]);
            if($validate !== true){
                $this->error($validate);
            }
            $billid = request()->post('id');
            
            $arr = explode(',', $billid);
            $info = (new billService())->billEntryIdInfo($arr);
            if (count($info) != count($arr)) {
                return json(['error' => '账单信息不完整']);
            }
            foreach($info as $inf){
                $data['pay_type']   = request()->post('pay_type');
                $data['gmt_payment'] = date('Y-m-d H:i:s',time());
                $data['status'] = 'TRADE_SUCCESS';
                $data['remarks'] = request()->post('remarks');
                $data['id'] = $inf['id'];
                //修改数据
                $billedit = (new billService())->billApiEdit($data);
                if($billedit){
                     $bill['id'][] = $inf['id'];
                    $bill['community_id'] = $inf['community_id'];
                    $bill['room_address'] = $inf['room_address'];
                    $bill['out_room_id'] = $inf['out_room_id'];
                    $bill['detailed'][] = '费用类型: '.$inf['cost_type'];
                    $bill['detailed'][] = '账期: '.$inf['acct_period'];
                    $bill['detailed'][] = '金额: '.$inf['bill_entry_amount'].'元';
                    $bill['trade_no'] = $inf['trade_no'];
                    $bill['pay_type'] = $data['pay_type'];
                    $bill['bill_entry_amount'][] = $inf['bill_entry_amount'];
                    $bill['gmt_payment'] = $data['gmt_payment'];
                    
                    $printinglist[] = $bill;  
                }else{
                    return json(['error' => '付款失败']);
                }
            }
            $printinglist = $printinglist[count($printinglist)-1];
            //根据小区编号查询打印机终端
            $community = (new billService())->communityMachine($printinglist['community_id']);
            $machineCode = $community['machine_code'];//终端号
            $community_name = $community['community_name'];//小区名称
            $room_address = $printinglist['room_address'];//门牌号
            $owner_name = (new billService())->billOwnerName($printinglist['out_room_id']);//业主姓名
            $detailed = $printinglist['detailed'];//费用类型
            $trade_no = $printinglist['trade_no'];//支付宝订单号
            $pay_type = $printinglist['pay_type'];//付款类型
            $bill_entry_amount = array_sum($printinglist['bill_entry_amount']);//支付金额
            $gmt_payment = $bill['gmt_payment'];//付款时间
            $property = (new billService())->propertyIdName($community['property_id']);//收款单位
            $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_entry_amount,$gmt_payment,$property);
            return '付款成功';
            return json(['info' => '付款成功']);
        }else{
            //获取账单数据
            $id = request()->get('id');
            $this->assign('id',$id);
            $id = explode(',',$id);
            $onekey = (new billService())->billEntryIdInfo($id);
            foreach($onekey as $inf){
                if($inf['status'] == 'TRADE_SUCCESS'){
                    return json(['error' => '账单已付款']);
                }
                
            }
            if (count($onekey) != count($id)) {
                return json(['error' => '账单信息不完整']);
            }
            //计算总金额
            $sum = (new billService())->billEntryIdInfoSum($id);
            $this->assign('sum',$sum);
            if(!empty($onekey)){
                foreach($onekey as $one){
                    //根据小区编号查询小区名称
                    $one['community_name'] = (new billService())->communityName($one['community_id'])['community_name'];
                    //根据房屋门牌号查询业主信息
                    $one['owner_name'] = (new billService())->billOwnerName($one['out_room_id']);
                    //数据从新存入数组
                    $list[] = $one;
                    $this->assign('onekey',$list);
                }
            }else{
                $this->assign('onekey',$onekey);
            }
            //查询缴费类型
            $paytype = (new billService())->paytype();
            $this->assign('paytype',$paytype);
            return $this->fetch('onekey_list2');
        } 
    }

    //一键收款查询
    public function onekeyBillList(){
        if(request()->isPost()){
            //获取账单数据
            $validate = $this->validate(request()->post(),[
                'id|账单' =>  'require',
                'pay_type|付款类型' => 'require'
            ]);
            if($validate !== true){
                return $validate;
                $this->error($validate);
            }
            $billid = request()->post('id');
            
            $arr = explode(',', $billid);
            $info = (new billService())->billEntryIdInfo($arr);
            if (count($info) != count($arr)) {
                return "账单信息不完整";
                return json(['error' => '账单信息不完整']);
            }
            foreach($info as $inf){
                if($inf["tongbu"]=="1"){
                    $api = new apiService(config('app')['roombilldel'], 'https://openapi.alipay.com/gateway.do');
                    //根据小区community_id查询物业token
                    $token = (new billService())->billinfoToken($inf['community_id']);
                    $res = $api->roomBillDel(json_encode(['community_id' =>  $inf['community_id'], 'bill_entry_id' => $inf['bill_entry_id'], 'token' => $token]));
    				if (isset($res['error'])) {
    					return json(['error' => $res['error']]);
    				}	
                }
                $data['pay_type']   = request()->post('pay_type');
                $data['gmt_payment'] = date('Y-m-d H:i:s',time());
                $data['status'] = 'TRADE_SUCCESS';
                $remarks=request()->post('remarks');
                if(!empty($remarks)){
                    $data['remarks'] = $remarks;
                }
                return "付款失败";
                $data['tongbu'] = 1;
                $data['id'] = $inf['id'];
                $data['onkeystatus'] = '1';
                //修改数据
                $billedit = (new billService())->billApiEdit($data);
                if($billedit){
                     $bill['id'][] = $inf['id'];
                    $bill['community_id'] = $inf['community_id'];
                    $bill['room_address'] = $inf['room_address'];
                    $bill['out_room_id'] = $inf['out_room_id'];
                    $bill['detailed'][] = '费用类型: '.$inf['cost_type'];
                    $bill['detailed'][] = '账期: '.$inf['acct_period'];
                    $str='金额: '.$inf['bill_entry_amount'].'元';
                    $bill_entry_amount=$inf['bill_entry_amount'];
                    
                    $bill['detailed'][] = $str;
                    $bill['trade_no'] = $inf['trade_no'];
                    $bill['pay_type'] = $data['pay_type'];
                    $bill['bill_entry_amount'][] = $bill_entry_amount;
                    $bill['gmt_payment'] = $data['gmt_payment'];
                    $printinglist[] = $bill;  
                }else{
                    return "付款失败";
                    return json(['error' => '付款失败']);
                }
            }
            $printinglist = $printinglist[count($printinglist)-1];
            //根据小区编号查询打印机终端
            $community = (new billService())->communityMachine($printinglist['community_id']);
            $machineCode = $community['machine_code'];//终端号
            if(!empty($machineCode)){
                $community_name = $community['community_name'];//小区名称
                $room_address = $printinglist['room_address'];//门牌号
                $owner_name = (new billService())->billOwnerName($printinglist['out_room_id']);//业主姓名
                $detailed = $printinglist['detailed'];//费用类型
                $trade_no = $printinglist['trade_no'];//支付宝订单号
                $pay_type = $printinglist['pay_type'];//付款类型
                $bill_entry_amount = array_sum($printinglist['bill_entry_amount']);//支付金额
                $gmt_payment = $bill['gmt_payment'];//付款时间
                $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_entry_amount,$gmt_payment,$property);
            }
            
            return 'ok';
            return json(['info' => '付款成功']);
        }else{
            //获取账单数据
            $id = request()->get('id');
            $this->assign('id',$id);
            $id = explode(',',$id);
            
            $onekey = (new billService())->billEntryIdInfo($id);
            foreach($onekey as $inf){
                if($inf['status'] == 'TRADE_SUCCESS'){
                    return json(['error' => '账单已付款']);
                }
            }
            if (count($onekey) != count($id)) {
                return json(['error' => '账单信息不完整']);
            }
            //计算总金额
            //$sum = (new billService())->billEntryIdInfoSum($id);
            $sum=0;
            if(!empty($onekey)){
                foreach($onekey as $one){
                    //根据小区编号查询小区
                    $communityinfo= (new billService())->communityName($one['community_id']);
                    $one['community_name']=$communityinfo['community_name'];
                    //根据房屋门牌号查询业主信息
                    $one['owner_name'] = (new billService())->billOwnerName($one['out_room_id']);
                    
                    $sum=$sum+$one['bill_entry_amount'];
                    //数据从新存入数组
                    $list[] = $one;
                    $this->assign('onekey',$list);
                }
            }else{
                $this->assign('onekey',$onekey);
            }
            $this->assign('sum',$sum);
            //查询缴费类型
            $paytype = (new billService())->paytype();
            $this->assign('paytype',$paytype);
            return $this->fetch('onekey_list');
        } 
    }
    //批量同步支付宝
    public function billUpload(){
        // 验证账单信息
        $id = explode(',',request()->param('id'));        
        $billlist = (new billService())->billEntryIdInfo($id);
        if (count($billlist) != count($id)) {
            return json(['error' => '账单信息不存在']);
        }
        //查询账单同步的状态
        $tongbu=Db::table("bill")->where("id","in",$id)->distinct("status")->field("tongbu")->select();
        if(count($tongbu)!="1"){
            return json(['error' => '已经同步的账单无法同步无法同步']);
        }
        if($tongbu[0]["tongbu"]=="1"){
            return json(['error' => '已经同步的账单无法同步无法同步']);
        }
        //查询账单缴费的状态TRADE_SUCCESS
        $status=Db::table("bill")->where("id","in",$id)->distinct("status")->field("status")->select();
        if(count($status)!="1"){
            return json(['error' => '已经缴费的账单无法同步']);
        }
        if($status[0]["status"]=="TRADE_SUCCESS"){
            return json(['error' => '已经缴费的账单无法同步']);
        }
        $community=Db::table("bill")->where("id","in",$id)->distinct("community_id")->field("community_id")->select();
        if(count($community)!="1"){
            return json(['error' => '账单不是同一小区无法批量同步']);
        }
        $community_id=$community[0]["community_id"];
        $batch_id=date('YmdHis', time()).\util\Tool::getRandomStr(6);//请求批次号;
        $token = (new roominfoService())->communityToken($community_id);
        if($token){
            $api = new apiService(config('app')['roombilladd'], 'https://openapi.alipay.com/gateway.do');
            $res = $api->roomBillAdd2(json_encode(['batch_id' => $batch_id, 'community_id' =>  $community_id,'token' => $token]),json_encode($billlist));
            if (!isset($res['error'])) {
                Db::table("bill")->where("id","in",$id)->update(["tongbu"=>"1","batch_id"=>$batch_id]);
                return json(['info' => '同步成功']); 
            }else{
                return json(['error' => $res['error']]);
            }
        }else{
            return json(['error' => 'token查询失败']); 
        }
        
        
    }
    

    //批量同步支付宝
    public function billUpload2(){
        // 验证账单信息
        $id = explode(',',request()->param('id'));        
        $info = (new billService())->billEntryIdInfo($id);
        if (count($info) != count($id)) {
            return json(['error' => '账单信息不存在']);
        }
        //循环将数据存入支付宝
        foreach($info as $data){
            if($data['tongbu'] == 1){
                return json(['error' => '账单已同步']); 
            }
            //根据小区community_id查询物业token
            $token = (new billService())->billinfoToken($data['community_id']);
            //查询业主姓名
            $remark_str = (new billService())->billOwnerName($data['out_room_id']);
            if($token){
                $api = new apiService(config('app')['roombilladd'], 'https://openapi.alipay.com/gateway.do');
                
                $res = $api->roomBillAdd(json_encode(['batch_id' => $data['batch_id'], 'community_id' =>  $data['community_id'], 'bill_entry_id' => $data['bill_entry_id'],'out_room_id' => $data['out_room_id'], 'room_address' => $data['room_address'], 'cost_type' => $data['cost_type'], 'bill_entry_amount' => $data['bill_entry_amount'], 'acct_period' => $data['acct_period'], 'release_day' => $data['release_day'], 'deadline' => $data['deadline'], 'remark_str' => $remark_str, 'token' => $token]));

                //判断是否存入支付宝
                if (!isset($res['error'])){
                    //更改账单状态
                    $status = (new billService())->billStatus($data['bill_entry_id']);
                    if(empty($status)){
                        return json(['error' => '账单同步失败']); 
                    }
                }else{
                    return json(['error' => $res['error']]); 
                }
            }else{
                return json(['error' => '账单信息错误']); 
            }
        }
        return json(['info' => '同步成功']);
    }

    //批量打印
    public function Printing(){
        //判断是否存在该数据
        $id = explode(',',request()->param('id'));
        $info = (new billService())->billEntryIdInfo($id);
        if (count($info) != count($id)) {
            return json(['error' => '账单信息不存在']);
        }
        foreach($info as $inf){
            if($inf['status'] == 'TRADE_SUCCESS'){
                $bill['id'][] = $inf['id'];
                $bill['community_id'] = $inf['community_id'];
                $bill['room_address'] = $inf['room_address'];
                $bill['out_room_id'] = $inf['out_room_id'];
                $bill['detailed'][] = '费用类型: '.$inf['cost_type'];
                $bill['detailed'][] = '账期: '.$inf['acct_period'];
                $bill['detailed'][] = '金额: '.$inf['bill_entry_amount'].'元';
                $bill['trade_no'] = $inf['trade_no'];
                $bill['pay_type'] = $inf['pay_type'];
                $bill['bill_entry_amount'][] = $inf['bill_entry_amount'];
                $bill['gmt_payment'] = $inf['gmt_payment'];
                $printinglist[] = $bill;
            }else{
                return json(['error' => '账单未付款,不能打印账单']);
            }
        }
        $printinglist = $printinglist[count($printinglist)-1];
        //判断是否已自动打印
        //根据小区编号查询打印机终端
        $community = (new billService())->communityMachine($printinglist['community_id']);
        $machineCode = $community['machine_code'];//终端号
        $community_name = $community['community_name'];//小区名称
        $room_address = $printinglist['room_address'];//门牌号
        $owner_name = (new billService())->billOwnerName($printinglist['out_room_id']);//业主姓名
        $detailed = $printinglist['detailed'];//费用类型
        $trade_no = $printinglist['trade_no'];//支付宝订单号
        $pay_type = $printinglist['pay_type'];//付款类型
        $bill_entry_amount = array_sum($printinglist['bill_entry_amount']).'元';//支付金额
        $gmt_payment = $bill['gmt_payment'];//付款时间
        $property = (new billService())->propertyIdName($community['property_id']);//收款单位
        $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_entry_amount,$gmt_payment,$property);
    }

    //查询账单
    public function billIdInfo($token,$community_id,$out_room_id){
        // 查询小区信息
        $token = $token;
        $data['community_id'] = $community_id;//小区ID
        $data['bill_status'] = null;
        $data['out_room_id'] = $out_room_id;//房屋编号
        $data['cost_type'] = null;
        $data['acct_period'] = null;
        $data['release_day'] = null;
        $data['batch_id'] = null;

        $api = new apiService(config('app')['roombilllist'],'https://openapi.alipay.com/gateway.do');
        $list = $api->roomBillList(json_encode(['community_id' => $data['community_id'], 'bill_status' => $data['bill_status'], 'out_room_id' => $data['out_room_id'], 'cost_type' => $data['cost_type'], 'acct_period' => $data['acct_period'], 'release_day' => $data['release_day'], 'batch_id' => $data['batch_id'], 'token' => $token]));
        dump($list);exit();
    }
	//删除账单
	public function billIdDel($token,$community_id,$bill_entry_id){
		$api = new apiService(config('app')['roombilldel'], 'https://openapi.alipay.com/gateway.do');
        $res = $api->roomBillDel(json_encode(['community_id' =>  $community_id, 'bill_entry_id' => $bill_entry_id, 'token' => $token]));
	}

    //---------------------------------------------------------------微信支付-------------------------------------------------------------------
    public function verification(){
        $code = request()->get('code');
        $community_id = request()->get('community_id');
        if(empty($community_id)){
            return '二维码信息错误';
        }
        //根据小区查询物业信息
        $communitylist = (new billService())->communityMachine($community_id);
        $this->assign('communitylist',$communitylist);
        $propertyinfo = (new billService())->propertyInfo($communitylist['property_id']);
        $appid = $propertyinfo['wx_appid'];//公众号的唯一标识
        $secret = $propertyinfo['wx_app_secret'];//AppSecret
        //用通过code换取网页授权access_token，同时获得openid
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);//要访问的地址
        curl_setopt($curl, CURLOPT_HEADER, 1);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);//设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//跳过ssl检查项
        curl_setopt($curl, CURLOPT_HEADER, 0);//显示返回的Header区域内容
        $tmpInfo = curl_exec($curl);//执行操作
        $err = curl_error($curl);//输出错误
        curl_close($curl);//关闭CURL会话
        $tmpInfo = $this->object_to_array(json_decode($tmpInfo));
        if(!empty($tmpInfo['errmsg'])){
            return $tmpInfo['errmsg'];
        }else{
            $openid = $tmpInfo['openid'];
            $this->assign('openid',$openid);
        }
        return $this->fetch('verification');
    }
    public function wxorder(){
        if(request()->post()){
            $data = request()->post();
            $room_address = $data['group'].$data['building'].$data['unit'].$data['room'];
            //根据小区和完整门牌号查询房屋信息
            $roomlist = (new billService())->roomAddress($data['community_id'],$room_address);
            if($data['name'] !== $roomlist['owner_name']){
                return json(['error' => '验证失败，请输入正确的业主姓名']);            
            }
            //根据房号查询账单
            $billlist = (new billService())->billRoomIdList($roomlist['out_room_id']);
            foreach($billlist as $list){
                $info['acct_period'][] = $list['acct_period'];
                $info['cost_type'][] = $list['cost_type'];
                $info['bill_entry_amount'][] = $list['bill_entry_amount'];
                $info['id'][] = $list['id'];
            }
            if(empty($info)){
                return json(['error' => '暂无可缴费账单']);            
            }
            $info['id'] = implode(',',$info['id']);
            $communitylist = (new billService())->communityMachine($data['community_id']);
            $info['community_name'] = $communitylist['community_name'];
            $info['address'] = $roomlist['address'];
            $info['owner_name'] = $roomlist['owner_name'];
            $info['bill_entry_amount_sum'] = array_sum($info['bill_entry_amount']);
            foreach ($info as $k => $v) {
                $this->assign($k, $v);
            }
            $this->assign('openid',$data['openid']);
            return $this->fetch('wxindex');
        }else{
            $id = explode(',',request()->get('id'));
            $openid = request()->get('openid');
            //根据账单ID查询微信信息
            $billinfo = (new billService())->billEntryIdInfo($id);
            if (count($billinfo) != count($id)) {
                return json(['error' => '账单信息不完整']);
            }
            //判断房号是否相同
            foreach($billinfo as $inf){
                $out_room_id[] = $inf['out_room_id'];
                $community_id[] = $inf['community_id'];
                //金额
                $bill_entry_amount[] = $inf['bill_entry_amount'];
            }
            $bill_entry_amount = array_sum($bill_entry_amount);
            $out_room_id = array_unique($out_room_id);
            if(count($out_room_id) !== 1){
                return json(['error' => '账单信息不是一户']);            
            }
            $community_id = array_unique($community_id);
            //根据小区查询物业信息
            $communityinfo = (new billService())->communityName($community_id[0]);
            $propertyinfo = (new billService())->propertyInfo($communityinfo['property_id']);
            //生成订单
            $order['appid'] = $propertyinfo['wx_appid'];//公众账号ID
            $order['mch_id'] = $propertyinfo['wx_mch_id'];//商户号
            //根据停车场查询子商户ID
            $order['sub_mch_id'] = $communityinfo['sub_mch_id'];//子商户公众账号ID
            $order['nonce_str'] = $this->createNoncestr();//随机字符串
            $order['body'] = $communityinfo['community_name'].'-物业缴费';//商品描述
            $order['out_trade_no'] = time().rand(100000,999999);//商户订单号
            $order['total_fee'] = $bill_entry_amount*100;//总金额
            $order['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
            $order['notify_url'] = 'https://www.jfzhiwen.com/admin/Bill/wxnotice';//通知url
            $order['trade_type'] = 'JSAPI';
            $order['openid'] = $openid;//用户标识
            $wxkey = $propertyinfo['wx_key'];//key
            $order['sign'] = $this->MakeSign($order,$wxkey);//签名
            //输出xml字符
            $xml = $this->ToXml($order);
            // return $xml;
            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
            //CURL模拟请求
            $curls = curl_init(); //启动一个CURL会话
            curl_setopt($curls, CURLOPT_URL, $url); //要访问的地址
            curl_setopt($curls, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curls, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curls, CURLOPT_HEADER, FALSE);//设置header
            curl_setopt($curls, CURLOPT_RETURNTRANSFER, TRUE);//要求结果为字符串且输出到屏幕上
            curl_setopt($curls, CURLOPT_POST, TRUE); //发送一个常规的Post请求
            curl_setopt($curls, CURLOPT_POSTFIELDS, $xml); //Post提交的数据包
            curl_setopt($curls, CURLOPT_TIMEOUT, 30); //设置超时限制防止死循环
            $payInfo = curl_exec($curls); //执行操作
            // $err = curl_error($curls);//输出错误
            curl_close($curls); //关闭CURL会话
            $payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            if($payInfo['return_code'] !== 'SUCCESS'){
                return $payInfo['return_msg'];
            }else{
                //添加进数据库
                $idlist = $id;
                foreach($idlist as $id){
                    $data['id'] = $id;
                    $data['trade_no'] = $order['out_trade_no'];
                    $billedit = (new billService())->billEdit($data);
                }
                //返回结果到前台唤起收银台
                if($billedit){
                    $jsApiParameters['appId'] = $payInfo['appid'];
                    $jsApiParameters['timeStamp'] = time();
                    // $jsApiParameters['nonceStr'] = $payInfo['nonce_str'];
                    $jsApiParameters['nonceStr'] = $this->createNoncestr();
                    $jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
                    $jsApiParameters['signType'] = 'MD5';
                    // $jsApiParameters['paySign'] = $payInfo['sign'];
                    $jsApiParameters['paySign'] = $this->MakeSigns($jsApiParameters,$wxkey);
                    return json(['jsApiParameters' => json_encode($jsApiParameters)]);
                }else{
                    return json(['info' => '订单存储失败']);
                }
            }
        }
    }
    //微信回调信息
    public function wxnotice(){
        $address = 'C:\phpStudy\WWW\zaozao\public\license\\'.'wxnotice'.time().rand(100000,999999).'.txt';//文本路径    
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        //获取异步返回的xml数据
        $xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $result = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        dump($result);exit();
        //验证回调信息
        if($result){
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                //根据支付宝交易号查询账单信息
                $order = (new orderService())->tradeOrderInfo($result['out_trade_no']);
                $data['id'] = $order['id'];
                $data['order_status'] = 'TRADE_SUCCESS';
                $data['pay_time'] = $result['time_end'];
                $data['pay_type'] = '微信';
                $data['status'] = 2;
                $orderedit = (new orderService())->orderEdit($data);
                //添加进数据库
                $recordinfo = (new orderService())->recordInfo($order['out_parking_id'],$order['car_number']);
                if(!empty($recordinfo)){
                    $info['id'] = $recordinfo['id'];
                    $info['out_time'] = date('Y-m-d H:i:s',time());
                    $info['parking_time'] = floor((strtotime($info['out_time'])-strtotime($recordinfo['in_time']))%86400/60);//停车时间
                    $info['status'] = 2;
                    $recordedit = (new orderService())->recordEdit($info);
                }
                if($orderedit){
                    $api = new apiService();
                    $result = $api->exitinfo(json_encode(['parking_id' => $order['parking_id'], 'car_number' =>  $order['car_number'], 'out_time' => $order['out_time']]));
                    $xmlTpl = "<xml><return_code><![CDATA[%s]]></return_code><return_msg><![CDATA[%s]]></return_msg></xml>";
                    return sprintf($xmlTpl,'SUCCESS','OK');
                }else{
                    echo '修改账单失败';
                } 
            }
        }
    }
    //将对象转换成数组
    public function object_to_array($obj){
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach($_arr as $key=>$val){
            if($key !== 'gioouts'){
                $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
                $arr[$key] = $val;
            }
        }
        return $arr;
    }


    
   
    

    //产生随机字符串，不长于32位
    public function createNoncestr($length = 32){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $str;
    }
    //生成签名
    protected function MakeSign($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }
    //生成签名
    protected function MakeSigns($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $result = md5($string);
        return $result;
    }
    //格式化参数格式化成url参数
    public function ToUrlParams($value){
        $buff = "";
        foreach($value as $k => $v){
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    //输出xml字符
    public function ToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key => $val){
            if (is_numeric($val)){
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }else{
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }


    
}